package com.jz.community.moduleshopping.address.ui;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.loaction.LocationActivity;
import com.jz.community.basecomm.loaction.LocationManager;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.commview.view.DividerItemDecoration;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.address.adapter.UserOrderAddressListAdapter;
import com.jz.community.moduleshopping.address.bean.BaseAddressInfo;
import com.jz.community.moduleshopping.address.bean.UserAddressInfo;
import com.jz.community.moduleshopping.address.task.GetAddressListTask;
import com.qmuiteam.qmui.widget.QMUIFloatLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Tony.Fan on 2018/6/20 09:04
 */
@Route(path = RouterIntentConstant.MODULE_SHOPPING_SELECT_ADDRESS_LIST)
public class SelectAddressActivity extends BaseMvpActivity {

    @BindView(R2.id.loc_select_back)
    ImageView locSelectBack;
    @BindView(R2.id.loc_select_title)
    TextView locSelectTitle;
    @BindView(R2.id.loc_select_toolbar)
    Toolbar locSelectToolbar;
    @BindView(R2.id.loc_select_near_title)
    TextView locSelectNearTitle;
    @BindView(R2.id.loc_select_near_float)
    QMUIFloatLayout locSelectNearFloat;
    @BindView(R2.id.loc_select_more_iv)
    ImageView locSelectMoreIv;
    @BindView(R2.id.loc_select_more_title)
    TextView locSelectMoreTitle;
    @BindView(R2.id.loc_select_more_rl)
    RelativeLayout locSelectMoreRl;
    @BindView(R2.id.loc_select_my_title)
    TextView locSelectMyTitle;
    @BindView(R2.id.loc_select_my_ll)
    LinearLayout locSelectMyLl;
    @BindView(R2.id.loc_select_my_rv)
    RecyclerView locSelectMyRv;

    private PoiSearch.Query query;
    private PoiSearch poiSearch;
    private LocationManager locationManager;
    private UserOrderAddressListAdapter userOrderAddressListAdapter;
    private BaseCommLocateInfo locateInfo;
    private List<BaseAddressInfo> userAdressInfoList = new ArrayList<>();
    private String lon;
    private String lat;
    private String city;
    private String cityCode;

    private static final int CODE_COMMUNITY = 0X00001;

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_loc_select;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(locSelectToolbar);
        locSelectTitle.setText("选择地址");
    }

    @Override
    protected void addListener() {
        super.addListener();
        locSelectBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        locSelectMoreRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(SelectAddressActivity.this, LocationActivity.class), CODE_COMMUNITY);
            }
        });
    }

    @Override
    protected void initDatas() {
        locationManager = new LocationManager();
        locateInfo = new BaseCommLocateInfo();
        getLocation();
        super.initDatas();
    }

    private void getUserAdress() {
        new GetAddressListTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                UserAddressInfo userAddressInfo = (UserAddressInfo) o;
                if (!Preconditions.isNullOrEmpty(userAddressInfo)) {
                    SHelper.vis(locSelectMyLl);
                    UserAddressInfo.EmbeddedBean embeddedBean = userAddressInfo.get_embedded();
                    handleBindUserAddressAdapter(embeddedBean);
                }
            }
        }).execute();
    }


    /**
     * 用户收货地址列表
     */
    private void handleBindUserAddressAdapter(UserAddressInfo.EmbeddedBean embeddedBean) {
        if (!Preconditions.isNullOrEmpty(embeddedBean) && !Preconditions.isNullOrEmpty(embeddedBean.getContent())) {
            LinearLayoutManager goods_layoutManager = new LinearLayoutManager(this);
            locSelectMyRv.setLayoutManager(goods_layoutManager);
            locSelectMyRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            Collections.reverse(embeddedBean.getContent());
            userOrderAddressListAdapter = new UserOrderAddressListAdapter(getUserAddressInfo(embeddedBean.getContent()), true);
            locSelectMyRv.setAdapter(userOrderAddressListAdapter);
            userOrderAddressListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    lon = userOrderAddressListAdapter.getData().get(position).getLongitude();
                    lat = userOrderAddressListAdapter.getData().get(position).getLatitude();
                    saveLocationMsg(userOrderAddressListAdapter.getData().get(position).getAddress());
                    setResult(RESULT_OK);
                    finish();
                }
            });
        }
    }

    /**
     * status (integer, optional): 状态(0正常 -1删除,默认正常:0)
     *
     * @param contentBeans
     * @return
     */
    private List<BaseAddressInfo> getUserAddressInfo(List<BaseAddressInfo> contentBeans) {
        for (BaseAddressInfo contentInfo : contentBeans) {
            filterUserAddressList(contentInfo);
        }
        return userAdressInfoList;
    }

    /**
     * 过滤用户地址
     *
     * @param contentInfo
     */
    private void filterUserAddressList(BaseAddressInfo contentInfo) {
        if (contentInfo.getStatus() == 0) {
            BaseAddressInfo contentBean = new BaseAddressInfo();
            contentBean.setId(contentInfo.getId());
            contentBean.setAddress(contentInfo.getAddress());
            contentBean.setAddress(contentInfo.getAddress());
            contentBean.setAddressDetails(contentInfo.getAddressDetails());
            contentBean.setIsDefault(contentInfo.getIsDefault());
            contentBean.setName(contentInfo.getName());
            contentBean.setLatitude(contentInfo.getLatitude());
            contentBean.setLongitude(contentInfo.getLongitude());
            contentBean.setPhone(contentInfo.getPhone());
            userAdressInfoList.add(contentBean);
        }
    }

    /**
     * 搜索附近地址
     */
    public void getLocation() {
        locationManager.getLocation(new LocationManager.GetLocationListener() {
            @Override
            public void OnResult(LocationManager.GetLocationResult result) {
                if (result.mResultId == 0) {
                    lon = result.mLocation.mLongitude + "";
                    lat = result.mLocation.mLatitude + "";
                    city = result.mLocation.mCity;
                    cityCode = result.mLocation.mCityCode;
                    searchNearAddress(result.mLocation.mLatitude, result.mLocation.mLongitude);
                }
                getUserAdress();
            }
        }, this);
    }

    /**
     * 搜索相关位置信息
     *
     * @param latitude
     * @param longitude
     */
    public void searchNearAddress(double latitude, double longitude) {
        query = new PoiSearch.Query("", "");
        query.setPageSize(10);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult arg0, int arg1) {
                LoggerUtils.fLog().i("PoiResult" + arg0);
                if (arg1 == AMapException.CODE_AMAP_SUCCESS) {
                    List<PoiItem> list = arg0.getPois();
                    int pageSize = Math.min(5, list.size());
                    for (int i = 0; i < pageSize; i++) {
                        PoiItem item = list.get(i);
                        locSelectNearFloat.addView(createTextView(item, item.getTitle()));
                    }
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem item, int rCode) {
            }
        });
        LatLonPoint point = new LatLonPoint(latitude, longitude);
        poiSearch.setBound(new PoiSearch.SearchBound(point, 2000, true));//搜索周边
        poiSearch.searchPOIAsyn();
    }

    /**
     * 创建Textview
     *
     * @param btnName
     * @return
     */
    private TextView createTextView(PoiItem item, String btnName) {
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, SHelper.dp2px(this, 25));
        lp.leftMargin = SHelper.dp2px(this, 5);
        TextView textView = new TextView(this);
        textView.setBackgroundResource(R.drawable.border_loc_near_gray);
        textView.setTextColor(ContextCompat.getColor(this, R.color.font_black));
        textView.setPadding(SHelper.dp2px(this, 10), 0, SHelper.dp2px(this, 10), 0);
        textView.setGravity(Gravity.CENTER);
        textView.setLayoutParams(lp);
        textView.setTextSize(14);
        textView.setText(btnName);
        addTvClick(item, textView);
        return textView;
    }

    private void addTvClick(PoiItem item, TextView tv) {
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = tv.getText().toString().trim();
                lat = item.getLatLonPoint().getLatitude() + "";
                lon = item.getLatLonPoint().getLongitude() + "";
                saveLocationMsg(title);
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_COMMUNITY && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    /**
     * 保存定位信息
     *
     * @param title
     */
    private void saveLocationMsg(String title) {
        locateInfo.lon = lon;
        locateInfo.lat = lat;
        locateInfo.city = city;
        locateInfo.citycode = cityCode;
        locateInfo.name = title;
        BaseSpUtils.getInstance().setCurrentCommuity(this, locateInfo);
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }
}
